package com.geekgo.ladder.core.aspect;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

/**
 * 切换数据源，不同方法调用不同数据源
 * @author geekgo
 * @version 2016/12/19 16:57
 */
public class DataSourceAspect {

    private final Logger LOG = LogManager.getLogger();

    @Pointcut("execution(* com.geekgo.ladder.provider..*.*(..))")
    public void aspect(){

    }

    /**
     * 配置前置通知，使用在aspect()方法上注册的切入点
     * @param point
     */
    @Before("aspect()")
    public void before(JoinPoint point){
        String className = point.getTarget().getClass().getName();
        String method = point.getSignature().getName();
        LOG.info("{}.{}({})",className,method, StringUtils.join(point.getArgs(),","));
        try{
            L:for (String key:ChooseDataSource.METHODTYPE.keySet()){
                for (String type:ChooseDataSource.METHODTYPE.get(key)){
                    if(method.startsWith(type)){
                        LOG.info("{}.{}-datasource({})",className,method,key);
                        HandleDataSource.putDataSource(key);
                        break L;
                    }
                }
            }
        }catch (Exception e){
            LOG.error(e);
            HandleDataSource.putDataSource("write");
        }
    }

    @After("aspect()")
    public void after(JoinPoint point){
        HandleDataSource.clear();
    }
}
